package game.engine.base

import android.graphics.*

open class Sprite @JvmOverloads constructor(
    var bitmap: Bitmap,
    x: Float = 0f,
    y: Float = 0f,
    degress: Float = 0f,
    ax: Float = 0.5f,
    ay: Float = 0.5f,
    sx: Float = 1.0f,
    sy: Float = 1.0f,
    zorder: Int = 0
) : Node(
    x = x,
    y = y,
    degress = degress,
    ax = ax,
    ay = ay,
    sx = sx,
    sy = sy,
    zorder = zorder
) {

    private val dstRect = RectF()
    val boundingRect = RectF()

    var width = 0f
    var height = 0f
    init {
        width = bitmap.width.toFloat()
        height = bitmap.height.toFloat()
        verticeDirty = true
    }

    fun updateBitmap(newBitmap:Bitmap){
        if (bitmap == newBitmap) return
        bitmap = newBitmap
        width = bitmap.width.toFloat()
        height = bitmap.height.toFloat()
        verticeDirty = true
    }

    override fun onDraw(canvas:Canvas) {
        canvas.setMatrix(finalMatrix)
        updateDstRect()
        canvas.drawBitmap(bitmap!!,null,dstRect,null)
    }

    fun getBoundingBox():RectF{
        boundingRect.set(x  - ax * width,  y - ay * height, x + (1f - ax) * width,  y + (1f - ay) * height)
        return boundingRect
    }

    private fun updateDstRect(){
        if (verticeDirty){
            dstRect.set(-ax * width,  -ay * height, (1f - ax) * width,  (1f - ay) * height)
            verticeDirty = false
        }
    }
}